<template>
  <div>
    <!-- 页面标题栏 -->
    <div class="page-header" style="margin-bottom: 20px;">
      <h2 style="color: #409EFF; font-size: 20px; margin-bottom: 0;">用户管理</h2>
    </div>
    
    <!-- 搜索和添加按钮区域 -->
    <div class="flex items-center mb-4">
      <el-input 
        v-model="searchUsername" 
        placeholder="请输入用户名" 
        @keyup.enter="fetchUsers" 
        class="flex-1 mr-4 custom-input" 
        size="default"
        :prefix-icon="Search"
      />
      <el-button 
        type="primary" 
        @click="addUser"
        size="default"
        :icon="Plus"
      >
        添加用户
      </el-button>
    </div>
    
    <!-- 用户表格 -->
    <el-card shadow="hover" class="mb-6" style="border-radius: 4px;">
      <el-table 
        :data="users" 
        stripe 
        border="false"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        header-row-class-name="table-header"
        class="custom-table"
      >
        <el-table-column prop="name" label="姓名" align="center" min-width="100" />
        <el-table-column prop="username" label="用户名" align="center" min-width="120" />
        <el-table-column prop="phone" label="手机号" align="center" min-width="120" />
        <el-table-column prop="role" label="用户角色" align="center" min-width="100" />
        <el-table-column prop="status" label="状态" align="center" min-width="80">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.status === 0" 
              type="danger"
              size="small"
            >
              已禁用
            </el-tag>
            <el-tag 
              v-if="scope.row.status === 1" 
              type="success"
              size="small"
            >
              已启用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="100" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="editUser(scope.row)"
              :icon="Edit"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      />
    </div>
    
    <!-- 修改用户对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="修改用户"
      width="500px"
      center
    >
      <el-form ref="userFormRef" :model="userForm" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />        
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />        
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="不修改请保持为空" />        
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" oninput="this.value = this.value.replace(/\D/g, '')" maxlength="11" />        
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择用户角色">
            <el-option label="普通用户" value="普通用户"></el-option>
            <el-option label="管理员" value="管理员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="已禁用" value="0"></el-option>
            <el-option label="已启用" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button type="primary" @click="saveEditUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加用户对话框 -->
    <el-dialog 
      v-model="addUserDialogVisible" 
      title="添加用户"
      width="500px"
      center
    >
      <el-form ref="addUserFormRef" :model="addUserForm" label-width="80px" :rules="addRules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addUserForm.name" placeholder="请输入姓名" />        
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名" />        
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password" placeholder="请输入密码" />        
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
          />
          <span v-if="passwordsDoNotMatch" style="color: red;">输入密码不一致</span>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="addUserForm.phone" 
            placeholder="请输入手机号" 
            oninput="this.value = this.value.replace(/\D/g, '')" 
            maxlength="11"
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="addUserForm.role" placeholder="请选择用户权限">
            <el-option label="普通用户" value="普通用户"></el-option>
            <el-option label="管理员" value="管理员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button type="primary" @click="saveAddUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axiosInstance from '../axiosInstance';
import { ElMessageBox } from 'element-plus';
import { Search, Plus, Edit } from '@element-plus/icons-vue';

const searchUsername = ref('');
const users = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const addUserDialogVisible = ref(false);
const loading = ref(false);
const userForm = ref({
  name: '',
  username: '',
  phone: '',
  address: '',
  role: '',
  status: '0', // 默认未启用
  password: '' // 新增密码字段，用于修改密码
});
const addUserForm = ref({
  name: '',
  username: '',
  phone: '',
  role: '',
  password: '',
  status: '1' // 默认未启用
});
const confirmPassword = ref('');
const passwordsDoNotMatch = ref(false);
const userFormRef = ref(null);
const addUserFormRef = ref(null);

// 表单验证规则 - 修改用户
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  password: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
});

// 表单验证规则 - 添加用户
const addRules = reactive({
  ...rules,
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
});

const fetchUsers = async () => {
  loading.value = true;
  try {
    const requestData = {
      username: searchUsername.value,
      page: currentPage.value,
      pageSize: pageSize.value
    };
    const response = await axiosInstance.post('/admin/list', requestData);
    if (response.data.code === '200') {
      users.value = response.data.data.listData;
      total.value = Number(response.data.data.total);
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if(error.response){
      const { status } = error.response;
      if (status === 401) {
      return;
      }
    }
    console.error(error);
    ElMessageBox.alert('获取用户列表失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  } finally {
    loading.value = false;
  }
};

const addUser = () => {
  addUserDialogVisible.value = true;
  addUserForm.value = {
    name: '',
    username: '',
    phone: '',
    role: '',
    status: '1', // 默认启用
    password: ''
  };
  confirmPassword.value = '';
  passwordsDoNotMatch.value = false;
  // 重置表单验证状态
  if (addUserFormRef.value) {
    addUserFormRef.value.resetFields();
  }
};

const saveEditUser = async () => {
  try {
    // 验证表单
    await userFormRef.value.validate();
    
    const response = await axiosInstance.put(`/admin/update`, userForm.value);
    if (response.data.code === '200') {
      ElMessageBox.alert('修改成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        customClass: 'center-message-box'
      });
      handleCloseEditDialog();
      fetchUsers();
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if (error === false) {
      return;
    }
    console.error(error);
    ElMessageBox.alert('修改失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const saveAddUser = async () => {
  try {
    // 验证表单
    await addUserFormRef.value.validate();
    
    if (addUserForm.value.password !== confirmPassword.value) {
      passwordsDoNotMatch.value = true;
      return;
    }
    passwordsDoNotMatch.value = false;
    
    const response = await axiosInstance.post('/admin/insert', addUserForm.value);
    if (response.data.code === '200') {
      ElMessageBox.alert('添加成功', '提示', {
        confirmButtonText: '确定',
        type: 'success',
        customClass: 'center-message-box'
      });
      handleCloseAddDialog();
      fetchUsers();
    } else {
      ElMessageBox.alert(response.data.message, '提示', {
        confirmButtonText: '确定',
        type: 'error',
        customClass: 'center-message-box'
      });
    }
  } catch (error) {
    if (error === false) {
      return;
    }
    console.error(error);
    ElMessageBox.alert('添加失败，请稍后重试', '提示', {
      confirmButtonText: '确定',
      type: 'error',
      customClass: 'center-message-box'
    });
  }
};

const editUser = (user) => {
  dialogVisible.value = true;
  userForm.value = {...user };
  // 确保 userForm.status 正确赋值为 user.status
  userForm.value.status = user.status.toString();
  // 重置密码字段，确保每次编辑时密码字段为空
  userForm.value.password = '';
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchUsers();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchUsers();
};

// 关闭修改对话框
const handleCloseEditDialog = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  dialogVisible.value = false;
};

// 关闭添加对话框
const handleCloseAddDialog = () => {
  if (addUserFormRef.value) {
    addUserFormRef.value.resetFields();
  }
  addUserDialogVisible.value = false;
  passwordsDoNotMatch.value = false;
};

fetchUsers();
</script>

<style scoped>
.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 1rem;
}

.flex-1 {
  flex: 1;
}

.mr-4 {
  margin-right: 1rem;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

/* 表格头部样式 */
.table-header {
  background-color: #f5f7fa;
  color: #409EFF;
}

/* 让消息框居中的样式 */
.center-message-box .el-message-box {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 动画效果 */
.el-button {
  transition: all 0.3s ease;
}

.el-table {
  transition: box-shadow 0.3s ease;
}

.el-card {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.el-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 输入框自定义样式 */
:deep(.custom-input) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  &:hover {
    border-color: #c0c4cc;
  }
  &:focus {
    border-color: #409EFF;
    outline: none;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

/* 表格自定义样式 */
:deep(.custom-table) {
  .el-table__cell {
    border-color: #ebeef5;
  }
  .el-table__header-wrapper {
    .el-table__header {
      .el-table__cell {
        background-color: #f5f7fa;
        color: #409EFF;
        font-weight: 500;
      }
    }
  }
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
    .el-table__cell {
      color: #606266;
    }
  }
}
</style>